﻿using Essensoft.AspNetCore.Payment.WeChatPay;
using Essensoft.AspNetCore.Payment.WeChatPay.Notify;
using Essensoft.AspNetCore.Payment.WeChatPay.Parser;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace EIP.Common.Pay.Notify
{
    public class WeChatPayNotifyUtil
    {
        /// <summary>
        /// 获取请求返回信息
        /// </summary>
        /// <returns></returns>
        public static async Task<WeChatPayUnifiedOrderNotify> GetUnifiedOrderNotify(HttpRequest request)
        {
            var body = await new StreamReader(request.Body, Encoding.UTF8).ReadToEndAsync();
            var parser = new WeChatPayXmlParser<WeChatPayUnifiedOrderNotify>();
            var notify = parser.Parse(body);
            if (string.IsNullOrEmpty(notify.ResponseBody))
            {
                throw new WeChatPayException("sign check fail: Body is Empty!");
            }
            if (notify.ResponseParameters.Count == 0)
            {
                throw new WeChatPayException("sign check fail: Parameters is Empty!");
            }
            if (!notify.ResponseParameters.TryGetValue("sign", out var sign))
            {
                throw new WeChatPayException("sign check fail: sign is Empty!");
            }
            return notify;
        }
    }
}